今天來算4位數的英數混和密碼
import hashlib
import random
import string
def generate_random_password():
# 生成隨機的4位英數混合密碼
characters = string.ascii_letters + string.digits
return ''.join(random.choice(characters) for _ in range(4))
def hash_password(password):
# 使用SHA-256哈希函數計算密碼的哈希值
return hashlib.sha256(password.encode()).hexdigest()
def find_collision(target_hash):
attempts = 0
while True:
random_password = generate_random_password()
hashed_password = hash_password(random_password)
attempts += 1
if hashed_password == target_hash:
return random_password, attempts
if __name__ == "__main__":
target_password = generate_random_password()
target_hash = hash_password(target_password)
collision_password, attempts = find_collision(target_hash)
print(f"目標密碼: {target_password}")
print(f"目標哈希值: {target_hash}")
print(f"碰撞密碼: {collision_password}")
print(f"經過 {attempts} 次嘗試找到碰撞")
目標密碼: Uzi2
目標哈希值: 1d5b7df7a06c9909791508982a8921b2e81385426d100653a045e9c38a49be57
碰撞密碼: Uzi2
經過 1440210 次嘗試找到碰撞
跟前一天純數字4位數字比起來,加上大小寫英文混合的4位數密碼就複雜了幾百倍,所以設密碼真的該設混合密碼比較安全。